package lecode01;


/**
 * 两数相加
 */
public class 两数相加2 {

    public static void main(String[] args) {
        MyNode myNode1 = new MyNode(9, new MyNode(9, new MyNode(9, new MyNode(9, new MyNode(9, new MyNode(9, new MyNode(9,null)))))));
        System.out.println(myNode1);
        MyNode myNode2 = new MyNode(9, new MyNode(9, new MyNode(9, new MyNode(9, null))));
        System.out.println(myNode2);
        MyNode myNode = addTwoNumbers(myNode1, myNode2,  0);
        System.out.println("res: " + myNode.toString());


    }

    public static MyNode addTwoNumbers(MyNode l1, MyNode l2,  int carry) {
        if (l1 == null && l2 == null && carry == 0) {
            return null;
        }
        //特别注意： 当其中一个链表短于另一个链表时，则补0处理
        int sum = (l1 !=null ? l1.getVal() : 0) + (l2 !=null ? l2.getVal() : 0) + carry;
        carry = sum / 10;
        if (sum >= 10){
            return new MyNode(sum % 10,addTwoNumbers((l1 !=null ? l1.next : null), l2 !=null ? l2.next:null, carry));
        }else {
            return new MyNode(sum ,addTwoNumbers(l1 !=null ? l1.next : null, l2 !=null ? l2.next : null, carry));
        }

    }
}


class MyNode {
    int val;
    MyNode next;

    public MyNode() {
    }

    public MyNode(int val) {
        this.val = val;
        this.next = null;
    }

    public MyNode(int val, MyNode next) {
        this.val = val;
        this.next = next;
    }

    public int getVal() {
        return val;
    }

    public int setVal(int val) {
        this.val = val;
        return val;
    }

    public MyNode getNext() {
        return next;
    }

    public MyNode setNext(MyNode next) {
        this.next = next;
        return next;
    }

    @Override
    public String toString() {
        return "MyNode{" +
                "val=" + val +
                ", next=" + next +
                '}';
    }
}
